// 添加基础URL配置
const API_BASE_URL = {
    LOCAL: 'http://localhost:8080',
    CLOUD: 'http://47.116.32.173:8080'
};

// 获取当前环境设置
function getCurrentBaseUrl() {
    const env = localStorage.getItem('apiEnvironment') || 'local';
    return env === 'local' ? API_BASE_URL.LOCAL : API_BASE_URL.CLOUD;
}

// 初始化环境切换
function initEnvironmentSwitch() {
    const envSelect = document.getElementById('apiEnvironment');
    if (envSelect) {
        // 设置初始值
        const currentEnv = localStorage.getItem('apiEnvironment') || 'local';
        envSelect.value = currentEnv;

        // 监听变化
        envSelect.addEventListener('change', function() {
            const newEnv = this.value;
            localStorage.setItem('apiEnvironment', newEnv);
            // 刷新页面以应用新的环境设置
            window.location.reload();
        });
    }
}

// DOM元素加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化环境切换
    initEnvironmentSwitch();
    
    // 检查登录状态
    if (sessionStorage.getItem('isLoggedIn') !== 'true') {
        window.location.href = 'index.html';
        return;
    }

    // 显示欢迎信息
    const username = sessionStorage.getItem('username');
    if (username) {
        document.getElementById('welcomeUsername').textContent = username;
    }

    // 初始化导航
    initNavigation();
    
    // 初始化实验卡片点击事件
    initExperimentCards();
    
    // 初始化容器控制
    initContainerControl();
    
    // 初始化个人中心标签页
    initProfileTabs();
    
    // 初始化搜索功能
    initSearch();

    // 实验卡片点击事件
    const experimentCards = document.querySelectorAll('.experiment-card');
    experimentCards.forEach(card => {
        const enterButton = card.querySelector('.btn-enter');
        if (enterButton) {
            enterButton.addEventListener('click', function() {
                const experimentId = card.getAttribute('data-experiment-id');
                const title = card.querySelector('h3').textContent;
                const description = card.querySelector('.card-body p').textContent;
                
                // 更新模态框内容
                document.querySelector('.modal-title').textContent = title;
                document.getElementById('modal-description').textContent = description;
                
                // 重置容器状态
                const containerStatus = document.getElementById('containerStatus');
                const containerInfo = document.getElementById('containerInfo');
                if (containerStatus && containerInfo) {
                    containerStatus.textContent = '未启动';
                    containerStatus.className = 'status-value';
                    containerInfo.style.display = 'none';
                }
                
                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('experimentModal'));
                modal.show();
            });
        }
    });

    // 下载实验指导书
    const downloadGuide = document.getElementById('downloadGuide');
    if (downloadGuide) {
        downloadGuide.addEventListener('click', function(e) {
            e.preventDefault();
            // TODO: 实现下载功能
            alert('正在准备下载实验指导书...');
        });
    }

    // 复制容器地址
    const copyAddressBtn = document.getElementById('copyAddress');
    if (copyAddressBtn) {
        copyAddressBtn.addEventListener('click', function() {
            const address = document.getElementById('containerAddress').textContent;
            navigator.clipboard.writeText(address).then(() => {
                this.innerHTML = '<i class="fas fa-check"></i>';
                setTimeout(() => {
                    this.innerHTML = '<i class="fas fa-copy"></i>';
                }, 2000);
            });
        });
    }

    // 启动容器
    const startContainerBtn = document.getElementById('startContainer');
    const stopContainerBtn = document.getElementById('stopContainer');
    let containerTimer = null; // 用于存储计时器ID

    if (startContainerBtn && stopContainerBtn) {
        startContainerBtn.addEventListener('click', function() {
            const statusElement = document.getElementById('containerStatus');
            const containerInfo = document.getElementById('containerInfo');
            const containerAddress = document.getElementById('containerAddress');
            
            if (!statusElement || !containerInfo || !containerAddress) return;

            // 更新状态为启动中
            statusElement.textContent = '启动中...';
            statusElement.className = 'status-value pending';
            this.disabled = true;
            
            // 模拟API调用
            setTimeout(() => {
                // 模拟返回的容器地址
                const address = 'http://practice.example.com:' + Math.floor(Math.random() * 1000 + 8000);
                
                // 更新状态
                statusElement.textContent = '运行中';
                statusElement.className = 'status-value running';
                containerInfo.style.display = 'block';
                containerAddress.textContent = address;
                
                // 切换按钮显示
                this.style.display = 'none';
                stopContainerBtn.style.display = 'inline-flex';
                
                // 开始倒计时
                startTimer();
            }, 2000);
        });

        // 关闭容器事件
        stopContainerBtn.addEventListener('click', function() {
            const statusElement = document.getElementById('containerStatus');
            const containerInfo = document.getElementById('containerInfo');
            
            if (!statusElement || !containerInfo) return;

            // 确认是否关闭容器
            if (confirm('确定要关闭容器吗？这将终止当前实验环境。')) {
                // 更新状态为关闭中
                statusElement.textContent = '关闭中...';
                statusElement.className = 'status-value pending';
                this.disabled = true;

                // 模拟API调用
                setTimeout(() => {
                    // 更新状态
                    statusElement.textContent = '已停止';
                    statusElement.className = 'status-value stopped';
                    containerInfo.style.display = 'none';

                    // 切换按钮显示
                    this.style.display = 'none';
                    startContainerBtn.style.display = 'inline-flex';
                    startContainerBtn.disabled = false;

                    // 清除计时器
                    if (containerTimer) {
                        clearInterval(containerTimer);
                        containerTimer = null;
                    }
                }, 1500);
            }
        });
    }

    // 计时器功能
    function startTimer() {
        let timeLeft = 2 * 60 * 60; // 2小时（秒）
        const timerElement = document.getElementById('remainingTime');
        if (!timerElement) return;
        
        // 清除可能存在的旧计时器
        if (containerTimer) {
            clearInterval(containerTimer);
        }
        
        containerTimer = setInterval(() => {
            timeLeft--;
            const hours = Math.floor(timeLeft / 3600);
            const minutes = Math.floor((timeLeft % 3600) / 60);
            
            timerElement.textContent = `${hours}小时${minutes.toString().padStart(2, '0')}分`;
            
            if (timeLeft <= 0) {
                clearInterval(containerTimer);
                containerTimer = null;
                const containerStatus = document.getElementById('containerStatus');
                const containerInfo = document.getElementById('containerInfo');
                const startContainerBtn = document.getElementById('startContainer');
                const stopContainerBtn = document.getElementById('stopContainer');
                
                if (containerStatus && containerInfo && startContainerBtn && stopContainerBtn) {
                    containerStatus.textContent = '已停止';
                    containerStatus.className = 'status-value stopped';
                    containerInfo.style.display = 'none';
                    startContainerBtn.style.display = 'inline-flex';
                    startContainerBtn.disabled = false;
                    stopContainerBtn.style.display = 'none';
                }
            }
        }, 1000);
    }

    // 个人中心标签切换
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            tabContents.forEach(content => {
                content.style.display = 'none';
                if (content.id === target) {
                    content.style.display = 'block';
                }
            });
        });
    });

    // 注销功能
    const logoutButton = document.querySelector('.logout');
    logoutButton.addEventListener('click', function(e) {
        e.preventDefault();
        if (confirm('确定要注销吗？')) {
            // 清除session存储
            sessionStorage.clear();
            // 重定向到登录页面
            window.location.href = 'index.html';
        }
    });

    // 实验开始按钮点击事件
    const startButtons = document.querySelectorAll('.btn-start');
    startButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation();
            const experimentId = this.getAttribute('data-experiment-id');
            // TODO: 实现实验启动逻辑
            console.log('Starting experiment:', experimentId);
        });
    });

    // 继续实验按钮点击事件
    const continueButtons = document.querySelectorAll('.btn-continue');
    continueButtons.forEach(button => {
        button.addEventListener('click', function() {
            const experimentId = this.getAttribute('data-experiment-id');
            // TODO: 实现继续实验逻辑
            console.log('Continuing experiment:', experimentId);
        });
    });

    // 页面加载时默认显示欢迎页面
    const welcomeLink = document.querySelector('[href="#welcome"]');
    if (welcomeLink) {
        welcomeLink.click();
    }
});

// 导航功能
function initNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    const sections = document.querySelectorAll('.content-section');
    
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            if (this.classList.contains('logout')) return;
            
            e.preventDefault();
            const target = this.getAttribute('href').substring(1);
            
            navItems.forEach(nav => nav.classList.remove('active'));
            this.classList.add('active');
            
            sections.forEach(section => {
                section.classList.remove('active');
                if (section.id === target) {
                    section.classList.add('active');
                }
            });
        });
    });
}

// 初始化实验卡片
function initExperimentCards() {
    const experimentCards = document.querySelectorAll('.experiment-card');
    experimentCards.forEach(card => {
        const enterButton = card.querySelector('.btn-enter');
        if (enterButton) {
            enterButton.addEventListener('click', function() {
                const experimentId = card.getAttribute('data-experiment-id');
                const courseId = card.getAttribute('data-course-id');
                const studentId = localStorage.getItem('studentId');
                
                if (!studentId) {
                    alert('请先登录！');
                    return;
                }

                // 发送选课请求
                fetch(`${getCurrentBaseUrl()}/enrollment/enroll`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Accept': 'application/json'
                    },
                    body: `studentId=${studentId}&courseId=${courseId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 选课成功后，更新模态框内容并显示
                        const title = card.querySelector('h3').textContent;
                        const description = card.querySelector('.card-body p').textContent;
                        
                        // 更新模态框内容
                        document.querySelector('.modal-title').textContent = title;
                        document.getElementById('modalExperimentDescription').textContent = description;
                        
                        // 重置容器状态
                        const containerStatus = document.getElementById('containerStatus');
                        const containerInfo = document.getElementById('containerInfo');
                        if (containerStatus && containerInfo) {
                            containerStatus.textContent = '未启动';
                            containerStatus.className = 'status-value';
                            containerInfo.style.display = 'none';
                        }
                        
                        // 显示模态框
                        const modal = new bootstrap.Modal(document.getElementById('experimentModal'));
                        modal.show();
                    } else {
                        alert('选课失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error('请求失败：', err);
                    alert('请求失败：' + err);
                });
            });
        }
    });
}

// 初始化容器控制
function initContainerControl() {
    const startButton = document.getElementById('startContainer');
    const stopButton = document.getElementById('stopContainer');
    const containerStatus = document.getElementById('containerStatus');
    const containerInfo = document.getElementById('containerInfo');
    const containerAddress = document.getElementById('containerAddress');
    const containerUrl = document.getElementById('containerUrl');
    const timerBox = document.getElementById('timerBox');
    const timerDisplay = document.getElementById('containerTimer');
    let containerTimer;
    
    // 启动容器
    startButton.addEventListener('click', function() {
        // 更新状态为启动中
        containerStatus.textContent = '启动中...';
        containerStatus.className = 'status-value pending';
        startButton.disabled = true;
        containerInfo.style.display = 'block';
        
        // 模拟API调用延迟
        setTimeout(() => {
            containerStatus.textContent = '运行中';
            containerStatus.className = 'status-value running';
            containerAddress.style.display = 'flex';
            containerUrl.textContent = 'http://localhost:8080';
            timerBox.style.display = 'flex';
            startButton.style.display = 'none';
            stopButton.style.display = '';
            
            // 启动计时器
            startTimer();
        }, 2000);
    });
    
    // 停止容器
    stopButton.addEventListener('click', function() {
        if (confirm('确定要关闭容器吗？实验环境将被清除。')) {
            // 更新状态为关闭中
            containerStatus.textContent = '关闭中...';
            containerStatus.className = 'status-value pending';
            stopButton.disabled = true;
            
            // 模拟API调用延迟
            setTimeout(() => {
                containerStatus.textContent = '已停止';
                containerStatus.className = 'status-value stopped';
                containerAddress.style.display = 'none';
                timerBox.style.display = 'none';
                stopButton.style.display = 'none';
                startButton.style.display = '';
                startButton.disabled = false;
                
                // 停止计时器
                clearInterval(containerTimer);
            }, 1500);
        }
    });
    
    // 复制地址
    document.getElementById('copyAddress').addEventListener('click', function() {
        const url = containerUrl.textContent;
        navigator.clipboard.writeText(url).then(() => {
            alert('地址已复制到剪贴板');
        });
    });
    
    // 计时器功能
    function startTimer() {
        let timeLeft = 2 * 60 * 60; // 2小时
        
        function updateTimer() {
            const hours = Math.floor(timeLeft / 3600);
            const minutes = Math.floor((timeLeft % 3600) / 60);
            const seconds = timeLeft % 60;
            
            timerDisplay.textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
            
            if (timeLeft === 0) {
                clearInterval(containerTimer);
                stopButton.click();
            } else {
                timeLeft--;
            }
        }
        
        updateTimer();
        containerTimer = setInterval(updateTimer, 1000);
    }
}

// 初始化个人中心标签页
function initProfileTabs() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content > div');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            tabBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            const target = this.textContent.toLowerCase().replace(/\s+/g, '-');
            tabContents.forEach(content => {
                content.classList.remove('active');
                if (content.classList.contains(target)) {
                    content.classList.add('active');
                }
            });
        });
    });
}

// 搜索功能
function initSearch() {
    const searchInput = document.getElementById('experiment-search');
    const searchBtn = document.getElementById('search-btn');
    
    if (searchInput && searchBtn) {
        searchBtn.addEventListener('click', function() {
            const searchTerm = searchInput.value.trim().toLowerCase();
            const cards = document.querySelectorAll('.experiment-card');
            
            cards.forEach(card => {
                const title = card.querySelector('h3').textContent.toLowerCase();
                const description = card.querySelector('.card-body p').textContent.toLowerCase();
                
                if (title.includes(searchTerm) || description.includes(searchTerm)) {
                    card.style.display = '';
                } else {
                    card.style.display = 'none';
                }
            });
        });
        
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchBtn.click();
            }
        });
    }
}

let courseCurrentPage = 1;
const coursePageSize = 10;
let courseHasNextPage = true;

function loadCourseList(page = 1, pageSize = 10) {
    fetch(`${getCurrentBaseUrl()}/course/list?page=${page}&pageSize=${pageSize}`)
        .then(res => res.json())
        .then(data => {
            if (data.code === 200) {
                courseHasNextPage = (data.data && data.data.length === pageSize);
                renderCourseCards(data.data || []);
                renderCoursePagination();
            } else {
                alert(data.message || '获取课程列表失败');
            }
        });
}

function renderCourseCards(courses) {
    const grid = document.querySelector('.experiment-grid');
    if (!grid) return;
    grid.innerHTML = '';
    courses.forEach(course => {
        const card = document.createElement('div');
        card.className = 'experiment-card';
        card.setAttribute('data-experiment-id', course.courseId);
        card.setAttribute('data-course-id', course.courseId);
        card.innerHTML = `
            <div class="card-header">
                <i class="fas fa-docker"></i>
                <h3>${course.name}</h3>
            </div>
            <div class="card-body">
                <p>${course.description}</p>
                <div class="card-meta">
                    <span><i class="fas fa-clock"></i> ${course.duration}小时</span>
                    <span><i class="fas fa-signal"></i> ${course.level}</span>
                </div>
            </div>
            <div class="card-footer">
                <button class="btn-enter" data-id="${course.courseId}">进入实验</button>
            </div>
        `;
        grid.appendChild(card);
    });
    
    // 绑定进入实验按钮事件
    document.querySelectorAll('.btn-enter').forEach(btn => {
        btn.onclick = function() {
            const courseId = this.getAttribute('data-id');
            const studentId = sessionStorage.getItem('studentId');
            
            if (!studentId) {
                alert('请先登录！');
                return;
            }

            // 发送选课请求
            fetch(`${getCurrentBaseUrl()}/enrollment/enroll`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'
                },
                body: `studentId=${studentId}&courseId=${courseId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    loadExperimentDetail(courseId);
                } else {
                    alert('选课失败：' + data.message);
                }
            })
            .catch(err => {
                console.error('请求失败：', err);
                alert('请求失败：' + err);
            });
        };
    });
}

function renderCoursePagination() {
    const grid = document.querySelector('.experiment-grid');
    if (!grid) return;
    let paginationDiv = document.getElementById('course-pagination');
    if (!paginationDiv) {
        paginationDiv = document.createElement('div');
        paginationDiv.id = 'course-pagination';
        paginationDiv.style.textAlign = 'center';
        paginationDiv.style.margin = '20px 0';
        grid.parentElement.appendChild(paginationDiv);
    }
    paginationDiv.innerHTML = `
        <button class="btn btn-secondary" ${courseCurrentPage === 1 ? 'disabled' : ''} id="course-prev-page">上一页</button>
        <span style="margin:0 12px; color:#fff;">第 ${courseCurrentPage} 页</span>
        <button class="btn btn-secondary" ${!courseHasNextPage ? 'disabled' : ''} id="course-next-page">下一页</button>
    `;
    document.getElementById('course-prev-page').onclick = function() {
        if (courseCurrentPage > 1) {
            courseCurrentPage--;
            loadCourseList(courseCurrentPage, coursePageSize);
        }
    };
    document.getElementById('course-next-page').onclick = function() {
        if (courseHasNextPage) {
            courseCurrentPage++;
            loadCourseList(courseCurrentPage, coursePageSize);
        }
    };
}

// 加载实验详情
function loadExperimentDetail(courseId) {
    fetch(`${getCurrentBaseUrl()}/course/${courseId}`)
        .then(res => res.json())
        .then(data => {
            if (data.code === 200) {
                showExperimentModal(data.data);
            } else {
                alert(data.message || '获取实验详情失败');
            }
        });
}

function showExperimentModal(course) {
    document.getElementById('modalExperimentTitle').textContent = course.name;
    document.getElementById('modalExperimentDescription').textContent = course.description;
    document.getElementById('modalExperimentDuration').textContent = `${course.duration}小时`;
    document.getElementById('modalExperimentDifficulty').textContent = course.level;
    // 实验指导书下载
    const guideBtn = document.getElementById('downloadGuide');
    if (course.guidePath) {
        guideBtn.style.display = '';
        guideBtn.onclick = () => window.open(course.guidePath, '_blank');
    } else {
        guideBtn.style.display = 'none';
    }
    // 其他字段可按需补充
    // 显示模态框
    new bootstrap.Modal(document.getElementById('experimentModal')).show();
}

// 页面加载时自动加载课程列表
if (document.querySelector('.experiment-grid')) {
    loadCourseList(courseCurrentPage, coursePageSize);
} 